package com.sikadwafastdaisfondturbo.pretloan.ui.process.page

import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaBaseAdapterUtil.getColor
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.ProcessCommonAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageProcessCommonBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BirthdayDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.CommonPopupWindow
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.event.track.TrackEventManager
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.ActivityStackHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程通用列表样式
 */
class CommonPage(): ProFragment() {
    private var _binding: PageProcessCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    var data: JSONObject? = null

    //内容列表
    var mCommonAdapter: ProcessCommonAdapter? = null
    var mSelectPosition = -1

    //出生日期选择
    private var mBirthdayDialog: BirthdayDialog? = null

    constructor(data: JSONObject): this(){
        this.data = data
    }

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageProcessCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRvList()
        EventBus.getDefault().register(this)
    }

    override fun initListener() {
        //下一步
        _binding?.btnNext?.setOnClickListener {
            onSikadwaSubProcessDataAction()
        }
    }

    override fun initData() {
        if (data == null){
            ActivityStackHelper.finishActivity(ProcessActivity::class.java)
            return
        }

        _binding?.stepTipsLayout?.visibility = View.GONE
        _binding?.contactAddOne?.visibility = View.GONE
        _binding?.approvedTipsLayout?.visibility = View.GONE
        //提交按钮由上级Activity显示
        _binding?.btnNext?.visibility = View.GONE
        data?.let {
            val stepTitle = it.optString("stepTitle")
            if ("personal_info" == stepTitle){
                _binding?.textStepTips?.setTextColor(getColor(R.color.FF4C8FFB))
                val showKey = getString(R.string.process_personal_info_tips_key)
                val showText = String.format(getString(R.string.process_personal_info_tips),showKey)
                val startIndex = showText.indexOf(showKey)
                val dataSecuritySpannable = SpannableString(showText)
                dataSecuritySpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF0040A8)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                //加粗
                dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                _binding?.textStepTips?.text = dataSecuritySpannable
                _binding?.stepTipsIcon?.setImageResource(R.mipmap.img_process_personal_info_tips_icon)
                _binding?.stepTipsLayout?.setBackgroundResource(R.drawable.process_personal_info_tips_bg)
                _binding?.stepTipsLayout?.visibility = View.VISIBLE
            }

            val dataList = arrayListOf<JSONObject>()
            val dataArray = it.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..< dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
            addEvent(String.format(EventType.PAGE.PAGE_STEP_COMMON_XX_START,it.optString("stepTitle")),"")
            mCommonAdapter?.data = dataList
        }
    }

    /**
     * 提交数据
     */
    private fun onSikadwaSubProcessDataAction(){
        _binding?.root?.clearFocus()
        if (!isAllowSubmit() || data == null){
            showToast(getString(R.string.tips_submit_error))
            return
        }

        data?.let {
            val params = JSONObject().addCommonParams().apply {
                put("path",it.optString("apiUrl").replace("/",""))
            }
            mCommonAdapter?.let { adapter ->
                for (i in 0..< adapter.itemCount){
                    val item = adapter.getItem(i)
                    if (item.has("selectItem")){
                        val selectItem = item.optJSONObject("selectItem")
                        if (selectItem != null){
                            params.put(item.optString("paramName"),selectItem.optString("value"))
                        }
                    }
                }
            }
            //立即上报
            TrackEventManager.trackEventNow(String.format(EventType.CLICK.CLICK_STEP_XX_NEXT,it.optString("stepTitle")),"")

            HHLog.e(">>>>>>提交数据>>>>>>>$params")
            val act = context as ProcessActivity
            act.submitAction(params)
        }
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRvList() {
        _binding?.rvCommon?.setHasFixedSize(true)
        _binding?.rvCommon?.isNestedScrollingEnabled = false
        _binding?.rvCommon?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.rvCommon?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.rvCommon?.addItemDecoration(LinearDecoration(0,0,0,topDecoration))
        mCommonAdapter = ProcessCommonAdapter(_binding?.rvCommon)
        _binding?.rvCommon?.adapter = mCommonAdapter
        _binding?.rvCommon?.itemAnimator = DefaultItemAnimator()
        mCommonAdapter?.setOnItemChildClickListener(onItemClickListener)
    }

    /**
     * 选择
     */
    private val onItemClickListener = SikadwaOnItemChildClickListener { parent, childView, position ->
        _binding?.root?.clearFocus()
        mSelectPosition = position
        mCommonAdapter?.let { adapter ->
            val item = adapter.getItem(position)
            when(item.optString("action")){
                "DATE_PICK" -> {//时间选择
                    showBirthDialog()
                }
                "SELECT" -> {//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = item.optJSONArray("values")
                    dataArray?.let {
                        for (i in 0..<it.length()){
                            dataList.add(it.optJSONObject(i))
                        }
                    }
                    showSelectPopupwindow(childView,dataList)
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        _binding?.let {
            val selectPopup = CommonPopupWindow(requireContext())
            selectPopup.setWindowWidth(view.width + DensityUtils.dp2px(10f))
            selectPopup.setSelectItemListener(object : CommonPopupWindow.IItemClickListener {
                //完成
                override fun onConfirmAction(data: JSONObject?) {
                    mCommonAdapter?.let { adapter ->
                        val item = adapter.getItem(mSelectPosition)
                        item.put("selectItem",data)
                        adapter.notifyItemChanged(mSelectPosition)

                        val subRemark = "${data?.optString("value")}$$${data?.optString("duration")}"
                        addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
                //关闭监听
                override fun onDismissListener() {
                }
            })
            selectPopup.show(view, it.root)
            selectPopup.setBrandList(dataList)
        }
    }

    /**
     * 选择出生日期
     */
    private fun showBirthDialog(){
        if (mBirthdayDialog == null){
            mBirthdayDialog = BirthdayDialog(context,"",object : BirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    mCommonAdapter?.let {
                        //可根据需要自行截取数据显示
                        val item = it.getItem(mSelectPosition)
                        val obj = JSONObject()
                        obj.put("title",selectDate.optString("showDate"))
                        obj.put("value",selectDate.optString("subDate"))
                        item.put("selectItem",obj)
                        it.notifyItemChanged(mSelectPosition)

                        addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),selectDate.optString("subDate"))
                    }
                }
            })
        }
        mBirthdayDialog?.show()
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        mCommonAdapter?.let { adapter ->
            for (i in 0..< adapter.itemCount){
                val item = adapter.getItem(i)
                //存在 isMust && isMust == ”NO“  非必填
                if (item.has("isMust") && item.optString("isMust") == "NO"){
                    continue
                }
                //必填 && 没有内容 || 内容为空
                if (!item.has("selectItem")){
                    isAllow = false
                    break
                }
                val selectItem = item.optJSONObject("selectItem")
                if (selectItem == null){
                    isAllow = false
                    break
                }
                if (selectItem.optString("value","").isEmpty()){
                    isAllow = false
                    break
                }
            }
        }
        return isAllow
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: String){
        when(event){
            Configs.Event.PROCESS_DATA_SUB -> {//上级点击提交
                onSikadwaSubProcessDataAction()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        data?.let {
            addEvent(String.format(EventType.PAGE.PAGE_STEP_COMMON_XX_END,it.optString("stepTitle")),"")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}